/*
 * @Date: 2025-08-10 01:22:07
 * @LastEditors: 贾二小 erxiao.jia@outlook.com
 * @LastEditTime: 2025-10-28 22:07:50
 * @FilePath: /admin-vue/src/composables/system/useAuth.ts
 */
import { http } from '@/plugins/axios'
import router from '@/plugins/router'
import { localStg } from '@/utils/storage'

export default () => {
  const form = reactive({
    username: 'admin',
    password: 'password',
  })

  //登录检测
  function isLogin(): boolean {
    return !!localStg.get(CacheEnum.TOKEN_NAME)
  }

  //退出登录
  async function logout() {
    await http.request({ url: `auth/logout`, method: 'POST' })
    localStg.remove(CacheEnum.TOKEN_NAME)
    router.push({ name: RouteEnum.LOGIN })
  }

  //登录
  const login = async () => {
    const { data } = await http.request<{ token: string; user: UserModel }>({
      url: `auth/login`,
      method: 'POST',
      data: form,
    })

    localStg.set(CacheEnum.TOKEN_NAME, data.token)
    useUserStore().setInfo(data.user)

    window.$notification?.success({
      title: '登陆成功',
      content: '欢迎回来，' + data.user.name,
      duration: 3000,
    })
    router.push({ name: RouteEnum.HOME })
  }

  const loadMenus = async () => {
    return await http.request<MenuModel[], ResponsePageResult<MenuModel>>({
      url: `menu`,
    })
  }

  const user = async () => {
    const { data } = await http.request<UserModel>({
      url: `auth/user`,
    })
    return data
  }

  const password = async (model: PasswordModel) => {
    const data = await http.request<any, ResponseResult<any>>({
      url: `auth/password`,
      method: 'PUT',
      data: model,
    })
    return data
  }

  return { isLogin, logout, loadMenus, login, form, user, password }
}
